package br.composer.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class NetworkUtilities {

	
	/**
	 * 
	 * @return local machine's IP 
	 * 
	 */
	public static String getLocalIp() {
		Enumeration<NetworkInterface> netInterfaces = null;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			System.out.println("Somehow we have a socket error...");
		}

		while (netInterfaces.hasMoreElements()) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> address = ni.getInetAddresses();
			while (address.hasMoreElements()) {
				InetAddress addr = address.nextElement();
				if (!addr.isLoopbackAddress() && !addr.isSiteLocalAddress()
						&& !(addr.getHostAddress().indexOf(":") > -1)) {
					return addr.getHostAddress();
				}
			}
		}
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			return "127.0.0.1";
		}
	}	
}
